﻿using OPCAutomation;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace AutoPrint.BJPT
{
    public class OPCClient
    {
        private static OPCServer Server;
        public OPCGroup Group;
        public OPCItem Item;
        public string ItemValue="";
        public DateTime TimeStamp = new DateTime();
        private readonly string TAG = ConfigurationManager.AppSettings["EunTag"];
        private readonly string RegexStr = ConfigurationManager.AppSettings["Regex"];

        public OPCClient()
        {
            Server = new OPCServer();
        }

        /// <summary>
        /// 二维码数据变化事件
        /// </summary>
        public event EventHandler EngineNumChanged;

        /// <summary>
        /// 开启OPC服务监听
        /// </summary>
        /// <returns></returns>
        public OPCGroup StartRun()
        {
            try
            {
                if (Server.ServerState != Convert.ToInt32(OPCServerState.OPCRunning))
                {
                    var serverName = ConfigurationManager.AppSettings["OPCServerName"];
                    Server.Connect(serverName);
                    Server.OPCGroups.DefaultGroupDeadband = 0;
                    Server.OPCGroups.DefaultGroupIsActive = true;
                    Server.OPCGroups.DefaultGroupUpdateRate = 25;
                    Group = Server.OPCGroups.Add("OPCGroup");
                    Group.IsSubscribed = true;
                    Item = Group.OPCItems.AddItem(TAG, 1000);
                    Group.DataChange += Group_DataChange;
                }
                return Group;
            }
            catch (Exception ex)
            {
                if(Server.ServerState == Convert.ToInt32(OPCServerState.OPCRunning))
                {
                    Server.Disconnect();
                }
                MessageBox.Show("OPC服务启动过程出错,错误信息:" + ex.Message);
                return Group;
            }
        }

        /// <summary>
        ///二维码采集事件触发
        /// </summary>
        /// <param name="TransactionID"></param>
        /// <param name="NumItems"></param>
        /// <param name="ClientHandles"></param>
        /// <param name="ItemValues"></param>
        /// <param name="Qualities"></param>
        /// <param name="TimeStamps"></param>
        private void Group_DataChange(int TransactionID, int NumItems, ref Array ClientHandles, ref Array ItemValues, ref Array Qualities, ref Array TimeStamps)
        {
            string itemValue = "";
            DateTime timeStamp = DateTime.Now;
            for (int i = 1; i <= NumItems; i++)
            {
                itemValue = ItemValues.GetValue(i) == null ? "" : ItemValues.GetValue(i).ToString() ;
                timeStamp = (DateTime)TimeStamps.GetValue(i);
                var isRegex = Regex.IsMatch(itemValue, RegexStr);

                //1.过滤软件开启后第一件2.过滤掉重复值3.符合正则匹配
                if (ItemValue != "" && itemValue != ItemValue && isRegex)
                {
                    ItemValue = itemValue;
                    TimeStamp = timeStamp;
                    EngineNumChanged?.Invoke(this,new EventArgs());
                }
                else if (ItemValue == "")
                {
                    ItemValue = itemValue;
                    TimeStamp = timeStamp;
                }
            }
        }

        /// <summary>
        /// 断开OPC服务器连接
        /// </summary>
        public void Disconnect()
        {
            if(Server.ServerState == Convert.ToInt32(OPCServerState.OPCRunning))
            {
                Server.Disconnect();
            }
        }
    }
}
